package com.ls.lserp.modules.material.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.entity.InventoryRequestEx;
import com.ls.lserp.modules.material.entity.MaterialRequestEx;
import com.ls.lserp.modules.material.entity.RequestExMaterial;
import com.ls.lserp.modules.material.service.InventoryRequestExService;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.ChangeMaterial;
import com.ls.lserp.modules.order.entity.SizeColorQuantity;
import com.ls.lserp.modules.order.entity.StyleFeedBack;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.produce.service.ProduceLicenseService;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/inventory/requestex/")
public class InventoryRequestExController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private InventoryRequestExService inventoryRequestExService;
	
	@Autowired
	private ProduceLicenseService produceLicenseService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public InventoryRequestEx get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return inventoryRequestExService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new InventoryRequestEx();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("inventory:requestex:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/material/inventoryRequestEx";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param inventoryRequestEx
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("inventory:requestex:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(InventoryRequestEx inventoryRequestEx, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "inventoryRequestEx");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 出库申请单号
		searchParam.append("&inventoryRequestNo=");
		searchParam.append(inventoryRequestEx.getInventoryRequestNo());
		// 生产制单号
		searchParam.append("&productionNo=");
		searchParam.append(inventoryRequestEx.getProductionNo());
		// 客户订单号
		searchParam.append("&indentNo=");
		searchParam.append(inventoryRequestEx.getIndentNo());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(inventoryRequestEx.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(inventoryRequestEx.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(inventoryRequestEx.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<InventoryRequestEx> page = inventoryRequestExService.findList(new Page<InventoryRequestEx>(request, response),inventoryRequestEx);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("inventoryRequestExs", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("inventoryRequestEx.ftl"), map);
		listMap.put("inventoryRequestEx", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
	 * 进入编辑页面
	 * @param inventoryRequestEx
	 * @param model
	 * @return
	 */
	@RequiresPermissions("inventory:requestex:edit")
	@RequestMapping(value = "form")
	public String form(InventoryRequestEx inventoryRequestEx,Model model,HttpSession session) {
		// 获取当前用户
				User curLoginUser = inventoryRequestEx.getCurrentUser();
		
		List<InventoryRequestEx> productionList = inventoryRequestExService.findProductionList();
		List<ProduceLicense> customerList = produceLicenseService.findCustomerList();
		inventoryRequestEx.setProductionList(productionList);
		if(inventoryRequestEx.getId() == null){
			inventoryRequestEx.setInventoryRequestNo("O.OTR."+DateUtils.getDate("yyyyMMddHHmmss"));
			// 出库单条码
			//inventoryRequestEx.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
			// 申请人
			inventoryRequestEx.setRequestUser(curLoginUser.getFirstName() + curLoginUser.getLastName());
			inventoryRequestEx.setRequestUserId(curLoginUser.getId());
			// 申请日期
			inventoryRequestEx.setRequestDate(new Date());
			
			// 下拉菜单（客供入库）
			inventoryRequestEx.setInventoryCategory(ResourcesUtil.getConfig("outbound_category_produce"));
			 //model.addAttribute("sequenceReturnCode", SequenceUtil.inventoryRequestEx().getReturnCode());
		}else{
		   	   // 查找出库申请明细
			   List<InventoryRequestEx> resultRequestList = inventoryRequestExService.findRequestDetail(inventoryRequestEx);
			   inventoryRequestEx.setRequestDetailsList(resultRequestList);
			   if (inventoryRequestEx.getInventoryRequestNo().indexOf("OMTM.") != -1) {
				   List<StyleOptionEntity> contractList = inventoryRequestExService.findContractInfo();
				   model.addAttribute("contractList",contractList);
				   model.addAttribute("imageStr","customizationUnitCost");
			   }else if (inventoryRequestEx.getInventoryRequestNo().indexOf("O.OTR.") != -1) {
				   model.addAttribute("imageStr","");
			   }else{
				   model.addAttribute("imageStr","produceNotice");
			   }
			   
		}
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("inventoryRequestEx", inventoryRequestEx);
		model.addAttribute("customerList", customerList);
		
		// 返回页面地址
		return "modules/material/inventoryRequestExCreate";
	}
	
	/**
	 * 生产制单联动
	 * @param model
	 * @return
	 */
	@RequiresPermissions("inventory:requestex:view")
	@RequestMapping(value = "productionFun")
	public String productionFun(InventoryRequestEx inventoryRequestEx,String imageStr, Model model,HttpSession session) {
		
		inventoryRequestEx = inventoryRequestExService.getProductionInfo(inventoryRequestEx);
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("inventoryRequestEx", inventoryRequestEx);
		model.addAttribute("imageStr",imageStr);
		// 返回页面地址
		return "modules/material/inventoryRequestExCreate";
	}
	
	/**
	 * 进入编辑页面
	 * @param orderMateriel
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = "findIndent")
	public String findIndent(InventoryRequestEx inventoryRequestEx,String imageStr,Model model) {
		
		List<ProduceLicense> indentList = produceLicenseService.findIndentNOList(inventoryRequestEx.getVenderId());
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("indentList", indentList);
		model.addAttribute("inventoryRequestEx", inventoryRequestEx);
		model.addAttribute("imageStr",imageStr);
		// 返回页面地址
		return "modules/material/inventoryRequestExCreate";
	}
	
	/**
	 * 订单联动获取各种数据
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = "findIndentInfo")
	public String findIndentInfo(ProduceLicense produceLicense,String imageStr,Model model) {
		BigcargoOrder bigcargoOrder = produceLicenseService.getIndentInfo(produceLicense);
		InventoryRequestEx inventoryRequestEx = new InventoryRequestEx();
		inventoryRequestEx.setIndentID(produceLicense.getIndentID());
		inventoryRequestEx = inventoryRequestExService.getProductionInfo(inventoryRequestEx);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("bigcargoOrder", bigcargoOrder);
		model.addAttribute("inventoryRequestEx", inventoryRequestEx);
		model.addAttribute("imageStr",imageStr);
		// 返回页面地址
		return "modules/material/inventoryRequestExCreate";
	}
    
   
   /**
    * 保存信息
    * @param inventoryRequestEx
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("inventory:requestex:edit")
   @RequestMapping(value = "save")
   @ResponseBody
   public String save(InventoryRequestEx inventoryRequestEx,  HttpServletResponse response) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if(inventoryRequestEx.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			InventoryRequestEx inventoryRequestExNew = get(inventoryRequestEx.getId().toString());
			// 判断数据是否删除
           if(inventoryRequestExNew==null || BaseEntity.DEL_FLAG_DELETE.equals(inventoryRequestExNew.getDeleteFlag())){
           	// 返回提示信息
           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
           }
			
           // 排他处理
		    if(inventoryRequestEx.getVersion()==get(inventoryRequestEx.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	inventoryRequestEx.setVersion(inventoryRequestEx.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}
	   
   	   // 保存入库申请
	   inventoryRequestExService.saveInventoryRequest(inventoryRequestEx);
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "inventory_requestex_save_success")));
   }
   
	/**
    * 进入查看页面
    * @param inventoryRequestEx
    * @param model
    * @return
    */
   @RequiresPermissions("inventory:requestex:view")
   @RequestMapping(value = "show")
   public String show(InventoryRequestEx inventoryRequestEx, Model model) {
	   
   	   // 查找出库申请明细
	   List<InventoryRequestEx> resultRequestList = inventoryRequestExService.findRequestDetail(inventoryRequestEx);
	   inventoryRequestEx.setRequestDetailsList(resultRequestList);
	   if (inventoryRequestEx.getInventoryRequestNo().indexOf("OMTM.") != -1) {
		   List<StyleOptionEntity> contractList = inventoryRequestExService.findContractInfo();
		   model.addAttribute("contractList",contractList);
		   model.addAttribute("imageStr","customizationUnitCost");
	   }else if (inventoryRequestEx.getInventoryRequestNo().indexOf("O.OTR.") != -1) {
		   model.addAttribute("imageStr","");
	   }else{
		   model.addAttribute("imageStr","produceNotice");
	   }
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("inventoryRequestEx", inventoryRequestEx);
       
       // 返回页面地址
       return "modules/material/inventoryRequestExShow";
   }
    
   /**
    * 导出定制出库申请单
    * @param response
    * @param styleOptionEntity
    * @return
    */
   @RequiresPermissions("inventory:requestex:view")
   @RequestMapping(value = "exportFile")
   public String exportFile(RequestExMaterial requestExMaterial,String contractNo,HttpServletResponse response) {
       try {
           String fileName = contractNo + "定制出库申请.xlsx";
           List<MaterialRequestEx> list = inventoryRequestExService.findRequestMaterial(requestExMaterial);
           new ExportExcel("", MaterialRequestEx.class, 2).setDataList(list).write(response, fileName).dispose();
           return null;
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
       }
       
       // 提示错误信息
       return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
     
   }
   
   /**
    * 导出定制出库申请单
    * @param response
    * @param styleOptionEntity
    * @return
    */
   @RequiresPermissions("inventory:requestex:view")
   @RequestMapping(value = "getNotOutboundNum")
   public String getNotOutboundNum(InventoryRequestEx inventoryRequestEx,HttpServletResponse response) {
	   int num = 0;
       try {
    	   
    	   num = inventoryRequestExService.getNotOutboundNum(inventoryRequestEx);
    	   
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
       }
       
       // 提示错误信息
       return renderString(response,num);
     
   }
   
   /**
    * @Title: 2017-04
    * @Description: 添加入库申请明细
    * @param @param addRequestDetails
    * @param @param model
    * @param @param session
    * @param @return
    * @return String 
    * @throws
    */

  @RequiresPermissions("inventory:requestex:view")
  @RequestMapping(value = "addRequestExDetails")
  public String addRequestExDetails(InventoryRequestEx inventoryRequestEx, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
    	  
  	       // 将page值赋值给mvc model层返回jsp页面
     	   model.addAttribute("inventoryRequestEx", inventoryRequestEx);
     	  
  	    
         // 返回地址
         return "modules/material/inventoryRequestExCreate";
      } catch (Exception e) {
          // 记录日志
          logger.error(e.getMessage(), e);
          
          // 返回地址
          return "modules/material/inventoryRequestExCreate";
      }
  }
  
  /**
   * @Title: delRequestDetail
   * @Description: 删除入库申请明细
   * @param @param inventoryRequest
   * @param @param model
   * @param @param session
   * @param @return
   * @return String 
   * @throws
   */

 @RequiresPermissions("inventory:requestex:view")
 @RequestMapping(value = "delRequestExDetails")
 public String delRequestExDetails(InventoryRequestEx inventoryRequestEx, HttpServletRequest request, HttpServletResponse response, Model model) {
     try {
   	  
    	 inventoryRequestEx.getRequestDetailsList().remove(inventoryRequestEx.getTrIndex());
  	   
 	       // 将page值赋值给mvc model层返回jsp页面
    	   model.addAttribute("inventoryRequestEx", inventoryRequestEx);
 	    
        // 返回地址
        return "modules/material/inventoryRequestExCreate";
     } catch (Exception e) {
         // 记录日志
         logger.error(e.getMessage(), e);
         // 返回地址
         return "modules/material/inventoryRequestExCreate";
     }
 }
   
}
